#-*- coding: utf-8 -*-

from usagi.paths import *
import gzip


def katakana(k):
    return u'ァ'<=k and k<=u'ー'

def hiragana(k):
    return u'ぁ'<=k and k<=u'ん'

class Kanji:
    def __init__(self,kan):
        self.str =kan
        self._parse_line()
        self.bushu=self._bushu()

    def __str__(self):
        return self.str        

    def _bushu(self):
        "Bushu number => Unicode bushu"
        return unichr(12031+self.B)

    def _get_kanji_line(self):
        f = gzip.open(KANJI_PATH,'r')
        dec = self.str.encode('utf-8')
        l = f.readline()
        while (l):
            if l.startswith(dec):
                return unicode(l,'utf-8')
            l=f.readline()
        return None

    def _parse_line(self):
        l = self._get_kanji_line()
        self.B = 0 # Radical number
        self.G = 0 # Grade in jouyoukanji
        self.S = 0 # Stroke count
        self.F = 0 # Frequency
        self.J = 0 # JLPT
        self.P = []# SKIP
        self.onyomi = []
        self.kunyomi= []
        self.nanori = []
        self.meaning= []
        l = l.split()
        nanori=False
        for i in l:
            if i[0]==u'B':
                self.B=int(i[1:])
            elif i[0]==u'G':
                self.G=int(i[1:])
            elif i[0]==u'S':
                self.S=int(i[1:])
            elif i[0]==u'F':
                self.F=int(i[1:])
            elif i[0]==u'J':
                self.J=int(i[1:])
            elif i[0]==u'P':
                self.P=i[1:].split('-')
            elif i[0]==u'T':
                nanori=True
            elif katakana(i[0]) or (i[0]==u'-' and katakana(i[1])):
                self.onyomi.append(i)
            elif hiragana(i[0]) or (i[0]==u'-' and hiragana(i[1])):
                if not nanori:
                    self.kunyomi.append(i)
                else:
                    self.nanori.append(i)
            elif i[0]==u'{':
                self.meaning.append(i[1:-1])

        
                

